package gameStates;

import gameStates.absGamesStates.AbsIngameState;
import gameStates.passes.AbsPassManagerState;
import settings.GraphicSettings;
import main.listeners.listenerClasses.gui.ChatActivatedEvent;
import main.listeners.listenerClasses.gui.ConsoleToggleEvent;
import main.listeners.listenerClasses.gui.GUIListener;
import main.listeners.listenerClasses.gui.IngameChangedEvent;
import main.listeners.listenerClasses.gui.ScoreBoardToggleEvent;
import main.listeners.listenerClasses.gui.SpawnMenuChangedEvent;

import com.jme.renderer.Renderer;
import com.jme.renderer.pass.BasicPassManager;
import com.jme.renderer.pass.ShadowedRenderPass;
import com.jme.system.DisplaySystem;

public class ShadowState extends PassGameState {
		
	private BasicPassManager pManager;
	private ShadowedRenderPass shadowPass;
	private AbsIngameState ingameState;
	
	public ShadowState(AbsIngameState ingameState, AbsPassManagerState passManagerState) {
		super("shadow", passManagerState);
		this.ingameState = ingameState;
		
		addListenerToClearer(new GUIListener() {
			@Override
			public void ingameChanged(IngameChangedEvent event) {
				setActive(event.isIngame() && GraphicSettings.get().getShadowEnabled());
			}
			
			@Override
			public void consoleToggled(ConsoleToggleEvent event) {
				enableInput(!event.getValue());
			}
			
			@Override
			public void spawnMenuChanged(SpawnMenuChangedEvent event) {}
			@Override
			public void scoreBoardToggled(ScoreBoardToggleEvent event) {}
			@Override
			public void chatActivated(ChatActivatedEvent event) {}
		});
	}
	
	public void updateShadowSettings() {
		pManager = new BasicPassManager();
		
		boolean enable = GraphicSettings.get().getShadowEnabled();
		shadowPass = new ShadowedRenderPass();
		shadowPass.add(ingameState.getRootNode());
		shadowPass.addOccluder(ingameState.getOccluders());
		shadowPass.setRenderShadows(true);
		shadowPass.setLightingMethod(ShadowedRenderPass.LightingMethod.Modulative);
		pManager.add(shadowPass);
		shadowPass.setEnabled(enable);
		setActive(enable);
	}
	
	@Override
	public void update(float tpf) {
		pManager.updatePasses(tpf);
	}
	
	@Override
	public void render(float tpf) {
		Renderer renderer = DisplaySystem.getDisplaySystem().getRenderer();
		renderer.clearBuffers();
		pManager.renderPasses(renderer);
	}
	
	@Override
	public void restore() {
		super.restore();
		if(ingameState.isInitialized()) updateShadowSettings();
	}
	
	@Override
	public void cleanup() {
		super.cleanup();
		if(pManager != null) pManager.cleanUp();
	}
}